<template>
  <div class="pic-container" :style="srcList.length ? {alignItems:'flex-start'} : {alignItems:'center'}">
    <!-- 初始卡片：未上传 -->
    <div class="upload-card" v-if="isEmpty">
      <div class="illustration">
        <img
          class="illus-img"
          mode="widthFix"
          src="@/assets/images/home/add_files.png"
        />
      </div>
      <div class="title">请上传图片</div>
      <div class="tips">
        <span>支持 PNG、JPG、JPEG、BMP</span>
        <span>大小不超过8MB</span>
      </div>
      <div class="upload-btn" @click="chooseLocalImage">上传图片</div>
    </div>

    <!-- hd: 单图预览 -->
    <div class="uploaded-wrapper" v-if="selectedMode === 'hd' && imageUrl">
      <img
        class="uploaded-img"
        :src="imageUrl"
        alt="已上传图片"
        @click="openViewer(0)"
      />
      <button class="delete-btn" type="button" @click="removeImageHd">×</button>
    </div>

    <!-- batch: 多图网格 -->
    <div
      class="uploaded-grid"
      v-if="selectedMode === 'batch' && srcList.length"
    >
      <div class="grid-item" v-for="(src, idx) in srcList" :key="src">
        <img
          class="grid-img"
          :src="src"
          alt="已上传图片"
          @click="openViewer(idx)"
        />
        <button class="grid-delete" type="button" @click="removeImageAt(idx)">
          ×
        </button>
      </div>
      <div class="grid-add" @click="chooseLocalImage">＋</div>
    </div>

    <el-image-viewer
      v-if="showPreview"
      show-progress
      :initial-index="currentIndex"
      :url-list="viewerList"
      @close="showPreview = false"
    >
    <template
        #toolbar="{ actions, reset, activeIndex }"
      >
        <el-icon @click="actions('zoomOut')"><ZoomOut /></el-icon>
        <el-icon
          @click="actions('zoomIn', { enableTransition: false, zoomRate: 2 })"
        >
          <ZoomIn />
        </el-icon>
        <el-icon
          @click="
            actions('clockwise', { rotateDeg: 180, enableTransition: false })
          "
        >
          <RefreshRight />
        </el-icon>
        <el-icon @click="actions('anticlockwise')"><RefreshLeft /></el-icon>
        <!-- <el-icon @click="download(activeIndex)"><Download /></el-icon> -->
      </template>
    </el-image-viewer>
    <!-- 全局隐藏文件输入，确保任何状态都可触发 -->
    <input
      ref="fileInput"
      type="file"
      :multiple="selectedMode === 'batch'"
      accept="image/png,image/jpeg,image/jpg,image/bmp"
      style="position: fixed; left: -9999px; width: 0; height: 0; opacity: 0"
      @change="handleFileSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import {
  Back,
  DArrowRight,
  Download,
  Refresh,
  RefreshLeft,
  RefreshRight,
  Right,
  ZoomIn,
  ZoomOut,
} from '@element-plus/icons-vue'

const props = defineProps<{ selectedMode: "hd" | "batch" }>();
const emit = defineEmits<{
  (e: "change", payload: File | File[] | string | string[] | null): void;
}>();

const MAX_SIZE_MB = 8;
const allowedTypes = new Set([
  "image/png",
  "image/jpeg",
  "image/jpg",
  "image/bmp",
]);

const fileInput = ref<HTMLInputElement | null>(null);
const imageUrl = ref<string>("");
const objectUrl = ref<string>("");

const showPreview = ref(false);
const currentIndex = ref(0);
const srcList = ref<string[]>([]);
const fileList = ref<File[]>([]);

const isEmpty = computed(() =>
  props.selectedMode === "hd" ? !imageUrl.value : srcList.value.length === 0
);
const viewerList = computed(() =>
  props.selectedMode === "hd" && imageUrl.value
    ? [imageUrl.value]
    : srcList.value
);

function chooseLocalImage() {
  fileInput.value?.click();
}

const handleFileSelect = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const files = input.files ? Array.from(input.files) : [];

  if (!files.length) return;
  const validated: File[] = [];
  for (const f of files) {
    if (!allowedTypes.has(f.type)) {
      ElMessage.error("仅支持 PNG、JPG、JPEG、BMP 格式");
      continue;
    }
    const sizeMb = f.size / (1024 * 1024);
    if (sizeMb > MAX_SIZE_MB) {
      ElMessage.error(`图片不能超过 ${MAX_SIZE_MB}MB`);
      continue;
    }
    validated.push(f);
  }
  if (!validated.length) {
    input.value = "";
    return;
  }

  if (props.selectedMode === "hd") {
    const f = validated[0];
    if (objectUrl.value) URL.revokeObjectURL(objectUrl.value);
    const url = URL.createObjectURL(f);
    objectUrl.value = url;
    imageUrl.value = url;
    // emit("change", [f]);
    convertFilesToBase64([f])
  } else {
    const newUrls: string[] = [];
    const newFiles: File[] = [];
    for (const f of validated) {
      const url = URL.createObjectURL(f);
      newUrls.push(url);
      newFiles.push(f);
    }
    srcList.value = srcList.value.concat(newUrls);
    fileList.value = fileList.value.concat(newFiles);
    console.log(fileList.value,'fileList.value')
    console.log(fileList.value.slice(),'fileList.value.slice()')
    await convertFilesToBase64(fileList.value.slice())

    // emit("change", fileList.value.slice());
  }

  input.value = ""; // 清空以便重复选择相同文件
};

const base64Files = ref<{ name: string; base64: string }[]>([]); // 存储 Base64 格式
// 将所有选中的文件转换为 Base64 并存储
const convertFilesToBase64 = (fileList: File[]) => {
  base64Files.value = []; // 清空旧数据
  const promises = fileList.map((file) => {
    return new Promise<{
      name: string;
      base64: string;
      size: number;
      width: number;
      height: number;
    }>((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const base64Data = reader.result as string;
        const img = new Image();
        img.onload = () => {
          resolve({
            name: file.name,
            base64: base64Data.split(",")[1], // 提取 Base64 数据部分
            width: img.width, // 图片宽度
            height: img.height, // 图片高度
            size: file.size, // 图片大小
          });
        };
        img.onerror = reject;
        img.src = base64Data;
      };
      reader.onerror = (error) => reject(error);
    });
  });

  Promise.all(promises)
    .then((results) => {
      base64Files.value = results; // 存储 Base64 数据
      emit("change", base64Files.value);
    })
    .catch((error) => console.error("Base64 转换失败", error));
};

function removeImageHd() {
  if (objectUrl.value) {
    URL.revokeObjectURL(objectUrl.value);
  }
  objectUrl.value = "";
  imageUrl.value = "";
  emit("change", "");
}

function removeImageAt(index: number) {
  srcList.value.splice(index, 1);
  fileList.value.splice(index, 1);
  emit("change", fileList.value.slice());
}

function openViewer(index: number) {
  currentIndex.value = index;
  showPreview.value = true;
}

const download = (index: number) => {
  const url = srcList.value[index]
  const suffix = url.slice(url.lastIndexOf('.'))
  const filename = Date.now() + suffix

  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      const blobUrl = URL.createObjectURL(new Blob([blob]))
      const link = document.createElement('a')
      link.href = blobUrl
      link.download = filename
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(blobUrl)
      link.remove()
    })
}

onBeforeUnmount(() => {
  if (objectUrl.value) {
    URL.revokeObjectURL(objectUrl.value);
  }
});
</script>

<style lang="scss" scoped>
.pic-container {
  display: flex;
  // align-items: center;
  // justify-content: center;
  width: 100%;
  height: 300px;
  overflow-y: auto; /* vertical scroll when content exceeds height */
  overflow-x: hidden; /* prevent horizontal scroll */
  background: rgba(255, 255, 255, 0.3490196078);
  border: 2px solid #fff;
  border-radius: 16px;
  .upload-card {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 8px 16px 0;
    .illustration {
      display: flex;
      align-items: center;
      justify-content: center;
      .illus-img {
        width: 120px;
      }
    }
    .title {
      font-size: 14px;
      font-weight: 600;
      color: #1f2d3d;
    }
    .tips {
      font-size: 12px;
      color: #6b7785;
      span {
        display: block;
        text-align: center;
      }
    }
    .upload-btn {
      width: 80%;
      height: 35px;
      margin-top: 8px;
      font-size: 14px;
      line-height: 35px;
      color: #fff;
      background: linear-gradient(270deg, #f8725d 0%, #e21510);
      border-radius: 28px;
      text-align: center;
    }
  }

  .uploaded-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    .uploaded-img {
      max-width: 100%;
      max-height: 100%;
      border-radius: 12px;
      cursor: zoom-in;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
    .delete-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      width: 28px;
      height: 28px;
      border: none;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.55);
      color: #fff;
      font-size: 18px;
      line-height: 28px;
      cursor: pointer;
    }
  }

  .uploaded-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    //width: 130%;
    .grid-item {
      position: relative;
      background: #fff;
      border-radius: 10px;
      overflow: hidden;
      .grid-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        cursor: zoom-in;
      }
      .grid-delete {
        position: absolute;
        top: 6px;
        right: 6px;
        width: 24px;
        height: 24px;
        border: none;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.55);
        color: #fff;
        font-size: 16px;
        line-height: 24px;
        cursor: pointer;
      }
    }
    .grid-add {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ff4d4f;
      font-size: 22px;
      background: #fff;
      border: 2px dashed #ffb3b3;
      border-radius: 10px;
      cursor: pointer;
      min-height: 70px;
      transition: all 0.2s ease;
      &:hover {
        border-color: #ff4d4f;
      }
    }
  }

  :deep(.img-full-dialog) {
    .el-dialog__header {
      padding: 8px 12px;
      background: #000;
      .el-dialog__title {
        color: #fff;
      }
      .el-dialog__headerbtn .el-dialog__close {
        color: #fff;
      }
    }
    .el-dialog__body {
      padding: 0;
      background: #000;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
    }
  }

  .preview-full-img {
    max-width: 100vw;
    max-height: 100vh;
    object-fit: contain;
    background: #000;
    display: block;
  }
}
</style>
